<?php

namespace App\Remote\OceanEngine;

use App\Models\Common\ConfigModel;
use App\Service\OpenShop\Feishu\ConfigService;
use Closure;
use Symfony\Component\HttpFoundation\Response as ResponseAlias;

class Remote extends \App\Remote\Remote
{
    public static function getBaseUri(): string
    {
        // TODO: Implement getBaseUri() method.
        return "https://ad.oceanengine.com";
    }

    public static function registerResponseHandle(): Closure
    {
        return function ($responseHttpCode, $responseOriginalContents) {
            if ($responseHttpCode == ResponseAlias::HTTP_OK && isJson($responseOriginalContents)) {
                $responseArr = jsonToArr($responseOriginalContents);
                if ($responseArr["code"] == 0) {
                    return $responseArr["data"] ?? [];
                }
            }
            throw new \Exception($responseHttpCode . "-" . $responseOriginalContents);
        }; // TODO: Change the autogenerated stub
    }

    public static function buildBasicHeaders(): array
    {
        if (static::class == AuthRemote::class) {
            return [
                "Content-Type" => "application/json"
            ];
        } else {
            // todo 获取巨量引擎token
            $authConfig = ConfigService::getConfigDetail("oceanEngine", "auth");
            $updatedAt  = $authConfig["updatedAt"]->timestamp;
            $auth       = $authConfig["value"];
            if (time() > $updatedAt + $auth["expires_in"]) {
                // todo 此时token 已过期
                $auth = AuthRemote::refreshToken($auth["refresh_token"]);
                // todo 更新巨量引擎token信息
                ConfigModel::query()->where([
                    "module" => "oceanEngine",
                    "name"   => "auth"
                ])->update([
                    "updatedAt" => time(),
                    "value"     => json_encode($auth, JSON_UNESCAPED_UNICODE)
                ]);
            }
            return [
                "Content-Type" => "application/json",
                "Access-Token" => $auth["access_token"]
            ];
        }
        // TODO: Change the autogenerated stub
    }


}
